package config

import (
	"context"
	"log"
	"math/rand"
	"protobuf-learn/proto"

	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

type service struct {
	name string
	proto.UnimplementedConfigServiceServer
}

func NewService(name string) *service {
	return &service{
		name: name,
	}
}

func (s *service) Flaky(ctx context.Context, req *proto.FlakyRequest) (*proto.FlakyResponse, error) {
	if rand.Intn(3) != 0 {
		log.Println("error response returned")
		return nil, status.Error(codes.Internal, "flaky error occurred")
	}

	log.Println("successful response returned")

	return &proto.FlakyResponse{}, nil
}

func (s *service) GetServerAddress(ctx context.Context, req *proto.GetServerAddressRequest) (*proto.GetServerAddressResponse, error) {
	log.Printf("request received: %s", s.name)

	return &proto.GetServerAddressResponse{Address: s.name}, nil
}
